package com.zdkj.edge.door.demo.service;



import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;

import com.zdkj.edge.door.demo.conf.AdmsConf;
import com.zdkj.edge.door.demo.model.api.ApiResponse;
import com.zdkj.edge.door.demo.model.api.ApiLoginData;
import com.zdkj.edge.door.demo.model.api.ApiLoginRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.time.Instant;

/**
 * 通用 ADMS 请求基类
 */
@Slf4j
public class AdmsApiBase {

  private AdmsConf admsConf;


  private final AtomicReference<String> apiToken = new AtomicReference<>();

  private Instant tokenExpireTime = Instant.EPOCH;

  public AdmsApiBase(AdmsConf admsConf) {
    this.admsConf = admsConf;
  }

  public Object doPostJsonResult(String path, Map<String, Object> paramMap) {
    refreshTokenIfNeeded();
    String fullUrl = getBaseUrl() + path;

    String jsonBody = JSONUtil.toJsonStr(paramMap);
    log.info("请求ADMS接口：url={}，参数={}", fullUrl, jsonBody);

    HttpRequest request = HttpRequest.post(fullUrl)
        .header(Header.CONTENT_TYPE, "application/json-patch+json")
        .header("ApiToken",  apiToken.get())
        .body(jsonBody)
        .timeout(admsConf.getTimeout());

    String body = request.execute().body();
    log.info("返回ADMS接口结果：{}", body);

    if (StringUtils.isBlank(body)) {
      return null;
    }

    return JSON.parse(body);
  }

  private void refreshTokenIfNeeded() {
    if (StringUtils.isBlank(apiToken.get()) || Instant.now().isAfter(tokenExpireTime)) {
      log.info("Token为空或已过期，执行登录...");
      ApiLoginRequest loginRequest = new ApiLoginRequest(admsConf.getUsername(), admsConf.getPassword());
      String loginUrl = getBaseUrl() + "/api/Login/Login/LoginApi";
      String jsonBody = JSONUtil.toJsonStr(loginRequest);

      String body = HttpRequest.post(loginUrl)
          .header(Header.CONTENT_TYPE, "application/json-patch+json")
          .body(jsonBody)
          .timeout(admsConf.getTimeout())
          .execute().body();

      log.info("登录返回结果：{}", body);

      ApiResponse<ApiLoginData> response = JSON.parseObject(body,
          new com.alibaba.fastjson.TypeReference<ApiResponse<ApiLoginData>>() {});

      if (response.getTag() == 1) {
        apiToken.set(response.getData().getApiToken());
        tokenExpireTime = Instant.now().plusSeconds(20 * 60 - 10); // 20分钟有效，提前失效
        log.info("登录成功，Token已更新");
      } else {
        throw new RuntimeException("登录失败：" + response.getMessage());
      }
    }
  }

  private String getBaseUrl() {
    return ("http://") + admsConf.getHost() + ":" + admsConf.getPort();
  }

  protected String getValidToken() {
    return apiToken.get();
  }
}
